import asyncio

from sqlalchemy import select

from dependencies.database import db

from admin.ai_models import transcriber as transcriber_impl  # 你需要提供
from models import meetings


async def _run_transcription(recording_id: int):
    tableModel = meetings.MeetingsRecording.__table__
    async with db.connection() as conn:
        # load recording
        where = [tableModel.c.id == recording_id]
        query = (select(tableModel).where(*where).select_from(tableModel)
                 .limit(1))
        rec = await conn.fetch_one(query)
        # to avoid circular import, import model now

        if not rec:
            print("[worker] recording not found:", recording_id)
            return

        # transcribe_callable: an async generator wrapper around your model
        async def transcribe_callable(recording_obj, chunk_seconds: int = 30):
            # example: transcriber_impl.transcribe_from_s3_key could download and yield segments
            # implement transcriber_impl.transcribe_from_s3_key(s3_key, chunk_seconds) as async generator
            async for seg in transcriber_impl.transcribe_from_s3_key(recording_obj.s3_key, chunk_seconds=chunk_seconds):
                yield seg

        # call service to do business logic (persist transcripts & update status)
        # await transcribe_and_persist(db, rec, transcribe_callable,
        #                              chunk_seconds=int(transcriber_impl.get_default_chunk_seconds()))


def transcribe_recording(recording_id: int):
    """Sync wrapper to be used with BackgroundTasks or Celery (calls the async runner)."""
    asyncio.run(_run_transcription(recording_id))
